<template>
  <px-dialog v-model="visible" :title="title" @close="cancel">
    <px-form ref="formRef" v-loading="loading" :model="formParams" :rules="rules" :validate-on-rule-change="false" inline label-width="100px">
      <px-row>
        <px-col :span="12">
          <px-form-item label="证照类型" prop="twoCode">
            <px-select v-model="formParams.twoCode" clearable filterable placeholder="请选择证照类型" style="width: 100%" @change="handleTypeChange">
              <px-option v-for="item in classificationList" :key="item.id" :label="item.name" :value="item.singleCode" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="证照名称" prop="threeCode">
            <px-select v-model="formParams.threeCode" placeholder="请选择证照名称" style="width: 100%" clearable>
              <px-option v-for="item in nameList" :key="item.value" :label="item.name" :value="item.singleCode" />
            </px-select>
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="颁证机构" prop="certificationAgency">
            <px-input v-model="formParams.certificationAgency" placeholder="请输入" maxLength="50" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="颁证日期" prop="certificationDate">
            <px-date-picker
              v-model="formParams.certificationDate"
              type="date"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择"
              style="width: 100%"
            />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="有效期至" prop="certificationDateValid">
            <px-date-picker
              v-model="formParams.certificationDateValid"
              type="date"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择"
              style="width: 100%"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="办证时间(天)" prop="certificationDealDate">
            <px-input-number v-model="formParams.certificationDealDate" placeholder="请输入" :min="1" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col v-if="activeTab.certificateType === 'DEVICE'" :span="12">
          <px-form-item label="设备编码" prop="equipNo">
            <px-select-v2
              v-model="formParams.equipNo"
              style="width: 100%"
              filterable
              clearable
              :options="typeIdList"
              placeholder="请选择"
              @change="changeEqpNo"
            />
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.certificateType === 'CERTIFICATE'" :span="12">
          <px-form-item label="持证人" prop="holder">
            <px-select v-model="formParams.holder" clearable filterable placeholder="请选择" style="width: 100%" @change="changeHolder">
              <px-option v-for="item in personList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.certificateType === 'DEVICE'" :span="12">
          <px-form-item label="设备名称" prop="equipName">
            <px-input v-model="formParams.equipName" placeholder="请选择设备编码" disabled clearable style="width: 100%" />
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.certificateType === 'CERTIFICATE'" :span="12">
          <px-form-item label="组织" prop="organization">
            <px-input v-model="formParams.organization" placeholder="请输入" clearable style="width: 100%" :readonly="handleType === 'EDIT'" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col v-if="activeTab.certificateType === 'CERTIFICATE'" :span="12">
          <px-form-item label="手机号" prop="phone">
            <px-input v-model="formParams.phone" placeholder="请输入" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.certificateType === 'CERTIFICATE'" :span="12">
          <px-form-item label="身份证号" prop="icCard">
            <px-input v-model="formParams.icCard" placeholder="请输入" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="24">
          <px-form-item label="证照附件" prop="pic">
            <FileUpload
              fileType="add"
              fileAccept="'pdf','png', 'jpg', 'jpeg', 'gif', 'bmp','webp'"
              :fileData="{ moduleName: 'eqp' }"
              :fileSize="fileSize"
              :fileList="fileList"
              :multiple="multiple"
              fileBtnText="上传文件"
              tipText="文件"
              @changeFileList="changeFileList"
            />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="24">
          <px-form-item label="备注" prop="remark">
            <px-input v-model="formParams.remark" placeholder="请输入" maxLength="200" clearable :rows="4" type="textarea" style="width: 100%" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>
    <template v-if="handleType !== 'VIEW'" #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="save">保存</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup>
import { computed, ref, reactive, toRefs, onMounted } from "vue";
import { getPersonListAPI } from "@/api/knowledge/documentManage";
import { getEqpListAPI, getSelectListAPI, updateCertificateInfoListAPI, certificateInfoCreateAPI, queryFileList } from "@/api/knowledge/certificate";
import { PxMessage } from "px-ui";
import FileUpload from "@/components/Upload/FileUpload.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ""
  },
  classificationList: {
    type: Array,
    default: () => []
  },

  handleType: {
    type: String,
    default: ""
  },
  classCode: {
    type: String,
    default: ""
  },
  activeTab: {
    type: Object,
    default: () => {}
  },
  rowData: {
    type: Object,
    default: () => {}
  },
  // 文档上传接口url
  actionUrl: {
    type: String,
    default: "/ifp/sharing/api/v1/file/upload",
    required: false
  }
});
const emits = defineEmits(["update:visible", "saveAction"]);

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const formRef = ref(null);

const state = reactive({
  loading: false,
  formParams: {
    pic: []
  },
  nameList: [],
  personList: [],
  typeIdList: [], // 设备编码下拉框
  modelIdList: [] // 设备名称下拉框
});

const fileList = ref([]);
const fileUploadList = ref([]);
const fileSize = ref(999);
const multiple = ref(true);
const { loading, formParams, nameList, personList, typeIdList, modelIdList } = toRefs(state);

const rules = computed(() => ({
  twoCode: [{ required: true, message: "证照类型不能为空", trigger: "change" }],
  threeCode: [{ required: true, message: "证照名称不能为空", trigger: "blur" }],
  holder: [{ required: true, message: "持证人不能为空", trigger: "change" }],
  phone: [{ required: false }, { pattern: /^1[3456789]\d{9}$/, message: "手机号格式错误", trigger: "blur" }],
  icCard: [{ required: false }, { pattern: /(^\d{15}$)|(^\d{17}([0-9]|X)$)/, message: "身份证号格式错误", trigger: "blur" }]
}));

onMounted(() => {
  if (props.handleType !== "ADD") {
    editSearch();
  }
  getPersonList();
  getEqpList();
});

// 获取证照名称下拉数据
const getNameList = async () => {
  try {
    let val = state.formParams.twoCode;
    let obj = props.classificationList?.find(i => i.singleCode === val) || {};
    const { certificateType, singleCode } = obj;
    let params = {
      classCode: props.classCode,
      certificateType: certificateType,
      parentSingleCode: singleCode,
      level: 3
    };
    const res = await getSelectListAPI(params);
    if (res?.length) {
      state.nameList = res;
    } else {
      state.nameList = [];
    }
  } catch (error) {
    console.log(error);
  }
};

const changeFileList = val => {
  fileUploadList.value = val.map(item => {
    return {
      id: item.id,
      originalName: item.originalName,
      fileName: item.fileName,
      fileType: item.fileType,
      fileSize: item.fileSize,
      fileUrl: item.fileUrl,
      accountId: item.accountId,
      accountName: item.accountName,
      status: item.status,
      createTime: item.createTime,
      updateTime: item.updateTime
    };
  });
};

const getPersonList = async () => {
  try {
    const res = await getPersonListAPI();
    if (res?.length) {
      res?.forEach(item => {
        item.id = item.userId;
        item.name = `${item.empNo}-${item.realName}`;
        // item.value = `${item.userId}-${item.empNo}-${item.realName}`;
        item.value = `${item.empNo}-${item.realName}`;
      });
      state.personList = res;
    } else {
      state.personList = [];
    }
  } catch (error) {
    console.log(error);
  }
};

const getEqpList = async () => {
  try {
    state.loading = true;
    const res = await getEqpListAPI({});
    if (res?.length) {
      state.typeIdList = res.map(item => ({ id: item.id, value: item.eqpId, label: item.eqpId, eqpId: item.eqpId, eqpName: item.eqpName }));
      state.modelIdList = res.map(item => ({ id: item.id, value: item.eqpName, label: item.eqpName, eqpId: item.eqpId, eqpName: item.eqpName }));
    } else {
      state.typeIdList = [];
      state.modelIdList = [];
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const changeEqpNo = val => {
  state.formParams.equipName = state.modelIdList.find(item => item.eqpId === val)?.label;
};

const cancel = () => {
  emits("update:visible", false);
};

// 查询证照信息
const editSearch = async () => {
  try {
    state.loading = true;
    const res = props?.rowData;
    const {
      twoCode,
      threeCode,
      deviceCode,
      deviceName,
      certificationAgency,
      certificationDate,
      certificationDealDate,
      certificationDateValid,
      files,
      holder,
      phone,
      organization,
      remark
    } = res;
    state.formParams = {
      twoCode,
      threeCode,
      equipNo: deviceCode,
      equipName: deviceName,
      certificationAgency,
      certificationDate: certificationDate,
      certificationDealDate: Number(certificationDealDate),
      certificationDateValid,
      pic: files,
      holder,
      phone,
      organization,
      remark
    };
    const filesAry = files?.filter(i => i !== "undefined");
    if (filesAry?.length) {
      const resFile = await queryFileList({ ids: files });
      fileList.value = resFile?.length ? resFile : [];
    }
    getNameList();
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const changeHolder = val => {
  const person = state.personList.find(item => item.value === val);
  state.formParams.organization = person?.deptName;
  state.formParams.phone = person?.phone || "";
};

const submitForm = async () => {
  try {
    state.loading = true;
    const { twoCode, threeCode, certificationAgency, certificationDate, certificationDealDate, certificationDateValid, remark } = state.formParams;
    const isEdit = props.handleType === "EDIT" ? true : false;
    const params = {
      id: isEdit ? props.rowData.id : "",
      classCode: props?.classCode,
      certificateType: props?.activeTab?.certificateType,
      twoCode,
      threeCode,
      certificationAgency,
      certificationDate,
      certificationDealDate,
      certificationDateValid,
      files: isEdit ? fileList.value?.map(i => String(i?.id)) : fileUploadList.value?.map(i => String(i?.id)),
      infoStatus: props.rowData.infoStatus,
      remark: remark
    };
    // 设备证照
    if (props?.activeTab?.certificateType === "DEVICE") {
      let deviceCode = typeIdList.value.filter(item => item.value === state.formParams.equipNo)[0]?.label;
      let deviceName = modelIdList.value.filter(item => item.value === state.formParams.equipName)[0]?.label;
      params.otherInfoConfig = {
        deviceCode: deviceCode,
        deviceName: deviceName
      };
    }
    // 人员证照
    if (props?.activeTab?.certificateType === "CERTIFICATE") {
      params.otherInfoConfig = {
        phone: state.formParams.phone,
        holder: state.formParams.holder,
        icCard: state.formParams.icCard,
        organization: state.formParams.organization
      };
    }
    if (isEdit) {
      await updateCertificateInfoListAPI(params);
      PxMessage.success("编辑成功");
    } else {
      await certificateInfoCreateAPI(params);
      PxMessage.success("保存成功");
    }
    emits("update:visible", false);
    emits("saveAction");
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 保存
const save = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitForm();
    }
  });
};

const handleTypeChange = val => {
  state.formParams.threeCode = "";
  if (val) {
    getNameList();
  } else {
    state.nameList = [];
  }
};
</script>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;
}

.upload-demo {
  width: 100%;
}
</style>
